package cn.wsalix.admin.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.anlaser.service.impl.ParentServiceImpl;
import cn.anlaser.utils.SearchFilter;
import cn.anlaser.utils.SearchFilter.Operator;
import cn.wsalix.admin.entity.SysDict;
import cn.wsalix.admin.form.DictForm;
import cn.wsalix.admin.repository.DictRepository;
import cn.wsalix.admin.service.DictService;
import cn.wsalix.admin.status.DictEnum;

@Service("dictService")
public class DictServiceImpl extends
		ParentServiceImpl<DictForm, DictRepository, SysDict> implements
		DictService {
	@Autowired
	private DictRepository dictRepository;

	@Override
	public String module() {
		return "/admin/dict";
	}

	@Override
	public DictRepository getRepository() {
		return dictRepository;
	}

	@Override
	public SysDict findByCodeOne(String code) {
		return dictRepository.findByCodeOne(code);
	}

	@Override
	public Class<SysDict> getEntityClazz() {
		return SysDict.class;
	}

	@Override
	public SysDict getNew(DictForm form) {
		return super.getNew(form);
	}

	@Override
	public Map<String, SearchFilter> buildByForm(DictForm form) {
		Map<String, SearchFilter> filters = buildFilter();
		if (form.getParentId() != null && form.getParentId() != 0) {
			filters.put("parent.id", new SearchFilter("parent.id", Operator.EQ,
					form.getParentId()));
		}
		if (form.getCode() != null && !form.getCode().equals("")) {
			filters.put("code",
					new SearchFilter("code", Operator.EQ, form.getCode()));
		}
		if (form.getStatus() != null) {
			filters.put("status", new SearchFilter("status", Operator.EQ, form
					.getStatus().ordinal()));
		}
		return filters;
	}

	@Override
	public Map<String, SysDict> getMapByCode(String code) {
		Map<String, SysDict> resMap = new HashMap<String, SysDict>();
		SysDict sysDict = findByCodeOne(code);
		if (sysDict != null) {
			for (SysDict obj : sysDict.getSubs()) {
				resMap.put(sysDict.getCode(), obj);
			}
		}
		return resMap;
	}

	@Override
	public List<SysDict> findSubsByCode(String code) {
		SysDict sysDict = findByCodeOne(code);
		if (sysDict == null) {
			return new ArrayList<SysDict>();
		}
		DictForm form = new DictForm();
		form.setParentId(sysDict.getId());
		form.setStatus(DictEnum.invocation);
		return findByForm(form);
	}

	@Transactional
	@Override
	public void forbidden(Long id) {
		SysDict sysDict = findById(id);
		sysDict.setStatus(DictEnum.forbidden);
		edit(sysDict);
	}

	@Transactional
	@Override
	public void invocation(Long id) {
		SysDict sysDict = findById(id);
		sysDict.setStatus(DictEnum.invocation);
		edit(sysDict);
	}

}
